const ws_address = "ws://" +
"127.0.0.1:5000";
let ws = new WebSocket(ws_address);
let connection_socketID = "";
let reconnect = false;
let message_queue = new Array();
let reconnectWaitBox = waitBox("等待重新与服务器建立连接...");
let wsReconnectLock = false;
resetWebsocketReconnectAction();
let status_icon_recv = new saveProcessBox("正在获取资源...", 0, 6);
var status_icon_recv_ok = false;

//websocket 重新连接
function wsReconnect() {
    if (!wsReconnectLock) {
        wsReconnectLock = true;
        reconnect = true;
        reconnectWaitBox.show();
        recreateWebsocketConnection();
        setTimeout(function () { wsReconnectLock = false; if (ws.readyState !== 1) { wsReconnect(); } }, 10000);
    }
}

let wsMsgQueueSender_Running = false;

//websocket 信息队列发送
function wsMsgQueueSender() {
    if (wsMsgQueueSender_Running) return false;
    wsMsgQueueSender_Running = true;
    while (ws.readyState == 1 && !reconnect && message_queue.length != 0) {
        console.log("<消息队列> 向服务器发送了一份数据");
        ws.send(JSON.stringify(message_queue.shift()));
    }
    if (message_queue.length != 0) {
        setInterval(wsMsgQueueSender, 2000);
        return false;
    } else {
        wsMsgQueueSender_Running = false;
        return true;
    }
}
//websocket 信息发送
function wsSender(msg, force = false) {
    msg["socketID"] = connection_socketID;
    msg["path"] = window.location.pathname;
    switch (true) {
        case ws.readyState != 1:
            console.log("<消息队列> WebSocket连接不正确,等待...")
            message_queue.push(msg);
            wsMsgQueueSender();
            break;
        case message_queue.length != 0 && !force:
            console.log("<消息队列> 消息队列等待中...");
            message_queue.push(msg);
            wsMsgQueueSender();
            break;
        case force:
            console.log("<消息&强制> 向服务器发送了一份数据");
            ws.send(JSON.stringify(msg));
            break;
        default:
            console.log("<消息> 向服务器发送了一份数据");
            ws.send(JSON.stringify(msg));
            break;
    }
    return null;
}
//websocket 安全断连
function wsDisconnect(statuscode = 1000) {
    wsSender({ "action": "disconnect", "username": username });
    setTimeout(ws.close, 2000, [statuscode, "<wsDisconnect> normal exit"]);
    return null;
}

//重设置websocket默认行为
function resetWebsocketReconnectAction() {
    ws.onclose = function (event) {
        console.log("<连接> 连接被关闭("+event["code"]+"),原因:" + event["reason"]);
        switch (event["code"]) {
            case 1000:
                reconnectWaitBox.show();
                wsReconnect();
                break;
            case 4000:
            default:
                reconnectWaitBox.show();
                console.log("<连接> 正在重启连接...");
                break;

        }
    }
    ws.onerror = function () {
        console.log("<连接> 连接出错");
        console.log("<连接> 正在重新连接...");
        errorBox("连接出错，正在重新连接...");
        reconnectWaitBox.show();
        wsReconnect();
    }
    ws.onopen = function () {
        console.log("<连接> 与服务器连接成功");
        if (reconnect) {
            try { if (!username) username = getCookie("username"); }
            catch (error) { username = getCookie("username"); }
            try { if (!password) password = getCookie("password"); }
            catch (error) { password = getCookie("password"); }
            if (username && password) {
                $("#userConnect").hide();
                $("#welcome").show();
                $("#welcome").text("正在获取用户信息...");
                $("#welcome").text("正在建立连接...");
                $("#welcome").text("等待服务器验证...");
                wsSender({ "action": "connect", "type": userConnectType, "username": username, "password": base64decode(password), "path": getUrlRelativePath() }, force = true);
            } else {
                $("#welcome").text("");
                $("#welcome").hide();
                $("#userConnect").fadeIn();
                userConnect();
            }
            reconnectWaitBox.close();
            successBox("重连成功");
            reconnect = false;
        }
    }
    ws.onmessage = function (event) {
        function escapeChars(str) {
            return str.replace(/&/g, '&')
                .replace(/</g, '<')
                .replace(/>/g, '>')
                .replace(/'/g, "'")
                .replace(/"/g, '"')
                .replace(/\|/g, '¦')
                .replace('\r', '');
        }
        event = JSON.parse(escapeChars(event.data));
        console.log("<消息> 接收到新信息");
        ActionManager(event);
    }
}
//重建websocket连接
function recreateWebsocketConnection() {
    try { ws.close(4000, "Connection Restart"); console.log("<连接> 重新启动WebSocket服务...") } catch (e) { null }
    ws = new WebSocket(ws_address);
    resetWebsocketReconnectAction();
}
//重定向
function redirect(target) {
    wsSender({ "action": "redirect", "username": username, "target": target },force=true);
};

//当页面加载完毕后调用，等同于$(document).ready()
$(function () {
    if (!ws || ws.readyState == 3 || ws.readyState == 4) {
        console.warn("websocket连接建立耗时过长");
        recreateWebsocketConnection();
    } else {
        status_icon_recv.show();
    }
});